<template>
    <div class="search-results">
        <!-- 搜索栏 -->
        <div class="search-box">
            <el-input v-model="searchQuery" placeholder="请输入搜索关键词" @keyup.enter="handleSearch">
                <template #append>
                    <el-button icon="Search" @click="handleSearch" />
                </template>
            </el-input>
        </div>

        <!-- 筛选条件 -->
        <!-- <div class="filters">
      <el-select v-model="sortField" placeholder="排序方式">
        <el-option label="相关度" value="relevance"/>
        <el-option label="最新" value="newest"/>
        <el-option label="最热" value="hot"/>
      </el-select>
      
      <el-cascader
        v-model="selectedCategory"
        :options="categoryOptions"
        placeholder="分类筛选"
        clearable
      />
    </div> -->

        <!-- 搜索结果 -->
        <div class="result-list">
            <el-skeleton :loading="loading" animated>
                <template #template>
                    <el-skeleton-item variant="rect" style="width: 100%; height: 120px; margin-bottom: 20px;"
                        v-for="index in 5" :key="index" />
                    <!-- 重复5个骨架 -->
                </template>

                <div v-for="item in results" :key="item.id" class="result-item">
                    <el-card shadow="hover" @click="navigateToEntry(item.id)">
                        <div class="item-header">
                            <h3>{{ item.title }}</h3>
                            <div class="meta">
                                <span>👁️ {{ item.view_count }}</span>
                                <span>⭐ {{ item.favorite_count }}</span>
                            </div>
                        </div>
                        <p class="summary">{{ item.summary }}</p>
                        <div class="category-tags">
                            <el-tag v-for="category in item.categories" :key="category.id" type="info" size="small">
                                {{ category.name }}
                            </el-tag>
                        </div>
                    </el-card>
                </div>
            </el-skeleton>

            <!-- 分页 -->
            <div class="pagination" v-if="totalCount > 0">
                <el-pagination background layout="prev, pager, next" :total="totalCount"
                        @current-change="handlePageChange" />
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getSearchResults, getCategoryTree } from '/@/api/encyclopedia'

const route = useRoute()
const router = useRouter()

// 搜索参数
const searchQuery = ref('')
const results = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)

// 筛选条件
const sortField = ref('relevance')
const selectedCategory = ref([])
const categoryOptions = ref([]) // 需要从API获取分类树



const formatCategories = (categories) => {
    return categories.map(cat => ({
        value: cat.id,
        label: cat.name,
        children: cat.children ? formatCategories(cat.children) : null
    }))
}

onMounted(async () => {
    searchQuery.value = route.query.keyword || ''
})

watch([sortField, selectedCategory], () => {
    currentPage.value = 1
    fetchResults()
})

// 获取搜索结果
const fetchResults = async () => {
    try {
        if (!searchQuery.value) return

        loading.value = true
        const params = {
            keyword: searchQuery.value,
            page: currentPage.value,
            page_size: pageSize.value,
            sort: sortField.value,
            category: selectedCategory.value.pop() || ''
        }

        const res = await getSearchResults(params)
        results.value = res.data.entries.map(item => ({
            ...item,
            categories: item.categories || [] // 防止undefined
        }))
        totalCount.value = res.data.total_count

        // 更新URL参数
        router.replace({
            query: {
                keyword: searchQuery.value,
                page: currentPage.value
            }
        })
    } catch (error) {
        ElMessage.error(`搜索失败：${error.message}`)
    } finally {
        loading.value = false
    }
}

// 搜索处理
const handleSearch = () => {
    router.push({
        path: '/search',
        query: { keyword: searchQuery.value.trim() }
    })
}

// 分页处理
const handlePageChange = (newPage) => {
    currentPage.value = newPage
    fetchResults()
}

// 监听路由变化
watchEffect(async () => {
    currentPage.value = parseInt(route.query.page) || 1
    await fetchResults()
})

// 跳转词条详情
const navigateToEntry = (id) => {
    router.push(`/entry/${id}`)
}
</script>

<style scoped>
.search-results {
    max-width: 1200px;
    margin: 20px auto;
    padding: 0 20px;
}

.search-box {
    margin-bottom: 30px;

    :deep(.el-input) {
        width: 600px;
    }
}

.filters {
    margin-bottom: 20px;

    .el-select {
        margin-right: 15px;
        width: 150px;
    }
}

.result-item {
    margin-bottom: 20px;
    cursor: pointer;

    .item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        h3 {
            margin: 0;
            font-size: 18px;
            color: var(--el-color-primary);
        }

        .meta {
            font-size: 0.9em;
            color: var(--el-text-color-secondary);

            span {
                margin-left: 15px;
            }
        }
    }

    .summary {
        color: var(--el-text-color-regular);
        margin: 10px 0;
        line-height: 1.6;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .category-tags {
        margin-top: 10px;

        .el-tag {
            margin-right: 8px;
        }
    }
}

.pagination {
    margin: 30px 0;
    display: flex;
    justify-content: center;
}
</style>
